# coding=utf-8


import fire
from tornado import ioloop, web
from tornado.httpserver import HTTPServer
from project import setting, urls
from db.model import db, User
from utils.loger import run_log
from pony.orm import db_session
import os
import webbrowser


def mapping_db(auto_create=False):
    db.bind('sqlite', setting.DB_SETTING['file'], create_db=auto_create)
    db.generate_mapping(create_tables=auto_create)


def run_server(host="127.0.0.1", port=1100):
    mapping_db()
    run_log.info("RUN init database success")
    app = web.Application(handlers=urls.url_handler, **setting.TORNADO_SETTING)
    server = HTTPServer(app)
    server.bind(port, address=host)
    server.start()
    webbrowser.open("http://%s:%s" % (host, port))
    run_log.info("RUN service is start up, you can visit http://%s:%s now" % (host, port))
    ioloop.IOLoop.instance().start()


@db_session
def create_user():
    mapping_db()
    account = input("account:")
    password = input("password:")
    user = User.create_user(account, password)
    print("create user:%s succeed!" % user.account)


def init_db():
    if os.path.exists(setting.DB_SETTING['file']):
        os.remove(setting.DB_SETTING['file'])
    mapping_db(True)

if __name__ == "__main__":

    fire.Fire({
        "initdb": init_db,
        "runserver": run_server,
        "newuser": create_user
    })

